<template>
<div>
  <el-upload list-type="picture-card" :limit="1" action="#" :on-preview="previews" :file-list="fileList" :class="{ disabled: fileComputed }" :on-remove="handelRemove" :on-change="changeFile" :before-upload="beforeUpload" :http-request="upload">
     <i class="el-icon-plus" />
  </el-upload>
  <el-progress style="width: 180px" :percentage="percent" v-if="showPercent" />
  <el-dialog :visible.sync='showDialog' title="图片预览">
    <img :src="Imgurl" alt="" style="width: 100%">
  </el-dialog>
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5' // 引入腾讯云的包
// 需要实例化
const cos = new COS({
  SecretId: 'AKIDf9ON5WgZBWaOwykGWVDeoiLiodBRSCgt',
  SecretKey: 'yg7HAn9E1YrugCRQ8ZkdFafU2JJ3XkgM'
}) 
export default {
  data () {
    return {
      fileList: [],
      showDialog: false,
      Imgurl: '',
      currentFileUid: '', // 用一个变量 记住当前上传的图片id
      percent: 0, // 当前的百分比
      showPercent: false
    }
  },
   computed: {
    // 设定一个计算属性 判断是否已经上传完了一张
    fileComputed() {
      return this.fileList.length === 1
    }
  },
  methods: {
    previews (file) {
      this.Imgurl = file.url
       this.showDialog = true
    },
    handelRemove (file, fileList) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
      // this.fileList = fileList
    },
    changeFile (file, fileList) {
       this.fileList = fileList.map(item => item)
    },
    beforeUpload (file) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
       if (!types.includes(file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      //  检查大小
      const maxSize = 5 * 1024 * 1024
      if (maxSize < file.size) {
        this.$message.error('图片大小最大不能超过5M')
        return false
      }
      this.currentFileUid = file.uid
      this.showPercent = true
      return true
    },
    upload (params) {
      if (params.file) {
        cos.putObject({
          Bucket: 'gagaga-106-1307936622', // 存储桶
          Region: 'ap-beijing', // 地域
          Key: params.file.name,              /* 必须 */
          StorageClass: 'STANDARD',
          Body: params.file, // 上传文件对象
          onProgress: (params) => {
            this.percent = params.percent * 100
          } 
        }, (err, data) => {
          if (!err && data.statusCode === 200) {
            // 表示上传成功，需要获取图片地址
            this.fileList = this.fileList.map(item => {
              if (item.uid === this.currentFileUid) {
                return { url: 'http://' + data.Location, upload: true }
              }
              return item
            })
            setTimeout(() => {
              // 重置百分比，并关闭进度条
            this.showPercent = false
            this.percent = 0
            }, 1000)
           }
        })
      }
    }
  }
}
</script>
<style>
.disabled .el-upload--picture-card {
  display: none
}
</style>
